/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pnt.server;

import java.io.IOException;
import java.net.*;
import java.util.Stack;
import java.util.Vector;
import java.util.logging.Logger;
import pnt.*;

/**
 *
 * @author andrew
 */
public class UDPConnection extends Connection {

    @SuppressWarnings("unused")
	private static Logger logger = Logger.getLogger("pnt.server"); 
    
    InetAddress address;
    int port;
    Vector<DatagramPacket> messageQueue;
    private boolean terminated = false;
    private DatagramSocket ds;
    
    UDPConnection(DatagramPacket dp, DatagramSocket primarySocket) {
        // this.protocol = new Protocol();
        this.address = dp.getAddress();
        this.port = dp.getPort();
        messageQueue = new Stack<DatagramPacket>();
        this.ds = primarySocket;
    }

    public int attentionNeeded() {
        if(terminated)
            return -1;
        if(!messageQueue.isEmpty())
            return 1;
        return 0;
    }

    public void run() {
        
        while (!messageQueue.isEmpty()){
            
            try {
                
                if (!messageQueue.isEmpty()){
                    DatagramPacket dp = messageQueue.remove(0);
                    PNTMessage m = new PNTMessage(dp.getData());

                    PNTMessage reply = handleReceivedMessage(m);
                    System.out.println("Message Received:" + m.toString());
                    
                    byte[] message = reply.getBytes();
                    DatagramPacket toSend = new DatagramPacket(message, message.length, address, port);
                    ds.send(toSend);
                    System.out.println("Message Sent:" + reply.toString());
                    
                }
                
            } catch (IOException ex) {
                
                System.err.println("Error sending udp message: " + ex);
                
            } catch (PNTMessage.MalformedPacketException ex){
            
                System.err.println("Malformed Packet Caught: " + ex);
            
            }
            
        }
        
    }

    public boolean close() {
        terminated = true;
        return terminated;
    }

    void addMessage(DatagramPacket dp) {
        messageQueue.add(dp);
    }

    public InetAddress getClientAddress() {
        return address;
    }

    public int getClientPort() {
        return port;
    }

    private PNTMessage handleReceivedMessage(PNTMessage m) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

}
